<?php


namespace services\buss;

use common\helpers\RedisHelper;
use common\models\base\CommonStatus;
use common\models\buss\Accounts;
use services\log\LogMemberOpService;
use Yii;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\buss\Platform;

class PlatformService extends Service
{
    /**
     * 平台列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function platformList(array $params, int $page, int $pageSize): array
    {
        $query = Platform::find()
            ->alias('p')
            ->select(['p.*', 'count(a.id) account_num'])
            ->leftJoin(Accounts::tableName() . ' a', 'a.platform_id = p.id and a.status in '. '('.Accounts::STATUS_ENABLE.','. Accounts::STATUS_INVALID.')')
            ->where([
                'p.status' => [
                    Platform::STATUS_ENABLE,
                    Platform::STATUS_INVALID
                ]
            ])->groupBy('p.id');
        if (isset($params['keywords']) && $params['keywords']) {
            $query->andWhere(['like', 'p.name', $params['keywords']]);
        }
        if (isset($params['platform_content_type']) && $params['platform_content_type']) {
            $query->andWhere(['like', 'p.platform_content_type', $params['platform_content_type']]);
        }
        if (isset($params['status']) && is_numeric($params['status'])) {
            $query->andWhere(['p.status' => $params['status']]);
        }

        $orderBy = [];
        if (isset($params['order_column']) && $params['order_column']) {
            $sort = isset($params['order_sort']) && $params['order_sort'] == 'asc' ? SORT_ASC : SORT_DESC;
            switch ($params['order_column']) {
                case 'account_num':
                    $orderBy['account_num'] = $sort;
                    break;
                default :
                    break;
            }
        }
        $orderBy['p.status'] = SORT_DESC;
        $orderBy['p.id'] = SORT_DESC;

        $list = $this->getListPageRes($query, $page, $pageSize, $orderBy);
        foreach ($list['list'] as &$val) {
            $platformType = json_decode($val['platform_content_type']);
            $platformTypeArr = [];
            $platformType1 = [];
            if ($platformType) {
                foreach ($platformType as $pt) {
                    $platformTypeArr[] = $pt ? Platform::$types[$pt] : '';
                    $platformType1[] = $pt ? intval($pt) : '';
                }
            }
            $val['platform_content_type'] = $platformType1;
            $val['platform_content_type_str'] = implode(' | ', $platformTypeArr);
            $val['status_name'] = CommonStatus::$statuss[$val['status']] ?? '';
        }
        return $list;
    }

    /**
     * 状态下拉筛选项
     * @return array[]
     */
    public static function getStatusCondition(): array
    {
        return [
            ['value' => Platform::STATUS_ENABLE, 'label' => Platform::$statuss[Platform::STATUS_ENABLE]],
            ['value' => Platform::STATUS_INVALID, 'label' => Platform::$statuss[Platform::STATUS_INVALID]],
        ];
    }

    /**
     * 平台内容类型下拉筛选项
     * @return array[]
     */
    public static function getTypeCondition(): array
    {
        return [
            ['value' => Platform::TYPE_VIDEO, 'label' => Platform::$types[Platform::TYPE_VIDEO]],
            ['value' => Platform::TYPE_IMAGE, 'label' => Platform::$types[Platform::TYPE_IMAGE]],
            ['value' => Platform::TYPE_CONTENT, 'label' => Platform::$types[Platform::TYPE_CONTENT]],
        ];
    }

    /**
     * 获取正常+禁用
     * @return Platform[]
     */
    public static function getNormalListByIds(): array
    {
        $query = Platform::find()
            ->select(['*'])
            ->where(['status' => [Platform::STATUS_ENABLE, Platform::STATUS_INVALID]]);
        return $query->orderBy(['id' => SORT_ASC])->all();
    }

    /**
     * 获取正常
     * @param array|int|null $orIds
     * @return CommonStatus[]
     */
    public static function getEnableListByIds($orIds = null): array
    {
        $query = Platform::find()
            ->select(['*'])
            ->where(['status' => Platform::STATUS_ENABLE]);
        if (!is_null($orIds)) {
            $query->orWhere(['id' => $orIds, 'status' => [Platform::STATUS_INVALID, Platform::STATUS_ENABLE]]);
        }
        return $query->orderBy(['id' => SORT_ASC])->all();
    }

    /**
     * 获取列表筛选项
     * @return array
     */
    public static function getListCondition(): array
    {
        return CommonHelper::getListCondition(self::getNormalListByIds(), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 获取编辑筛选项
     * @param array|int|null $orIds
     * @return array
     */
    public static function getEditCondition($orIds = null): array
    {
        return CommonHelper::getListCondition(self::getEnableListByIds($orIds), ['value_column' => 'id', 'label_column' => 'name']);
    }

    /**
     * 更新平台
     * @throws \Exception
     */
    public function updatePlatform(array $params)
    {
        $platform = new Platform();
        // 是否为编辑，编辑判断排除当前ID
        $whereId = [];
        $scenario = 'create';
        $oldPlatform = null;
        if ($params['id']) {
            $whereId = ['!=', 'id', $params['id']];
            // 账号表
            $platform = Platform::findOne($params['id']);
            $oldPlatform = self::getData($params['id']);
            $scenario = 'edit';
        }
        // 判断名称是否存在
        $check = Platform::find()
            ->select(['id'])
            ->where([
                'name' => $params['name'],
                'status' => [Platform::STATUS_ENABLE, Platform::STATUS_INVALID]
            ])
            ->andWhere($whereId)
            ->asArray()
            ->one();
        if ($check) {
            return CommonHelper::api(422, '该名称已存在');
        }

        $platform->name = $params['name'];
        $platform->platform_content_type = explode(',', CommonHelper::strFormat($params['platform_content_type']));
        $platform->authenticator_rules = $params['authenticator_rules'] ?: '';
        $platform->status = $params['status'];
        $platform->operation_id = Yii::$app->user->identity->member_id;
        $platform->operation_name = Yii::$app->user->identity->member->realname;
        $platform->saveAndCheckResult();

        // 添加日志
        LogMemberOpService::createPlatformLog($scenario, $platform, $oldPlatform);
        // 更新缓存
        RedisHelper::setPlatform($platform);
        return $platform->id;
    }

    /**
     * 平台数据
     * @param int $id
     * @return Platform|null
     */
    public static function getData(int $id): ?Platform
    {
        return Platform::findOne($id);
    }

    /**
     * 平台删除
     * @throws \Exception
     */
    public function deletePlatform(array $params): array
    {
        // 平台状态更新为-1
        Platform::updateAll([
            'status' => Platform::STATUS_DELETE,
            'operation_id' => Yii::$app->user->identity->member_id,
            'operation_name' => Yii::$app->user->identity->member->realname,
            'updated_at' => time()
        ], ['id' => $params['id']]);

        // 添加日志
        LogMemberOpService::createPlatformLog('delete',  self::getData($params['id']));
        // 删除缓存
        RedisHelper::delPlatform($params['id']);
        return ['id' => $params['id']];
    }
}
